
package com.mephi.controller.action;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import com.mephi.controller.GameIteratorWrapper;
import com.mephi.gui.GUI;
import com.mephi.gui.Piece;
import com.mephi.interfaces.GameIterator;
import com.mephi.model.PieceMovement;
import com.mephi.util.CastlingSort;
import com.mephi.util.Constants;
import com.mephi.util.PieceColor;
import com.mephi.util.PieceSort;

/**
 * Implementation of behavior for button called btnNext 
 * @author mephisto
 * 2011-06-14
 */
public class BtnNextAction implements ActionListener
{
	@Override
	public void actionPerformed(ActionEvent arg0)
	{
		GameIterator git = GameIteratorWrapper.INSTANCE.getGameIterator();
		PieceMovement pm = git.nextPieceMovement();
		String tab[] = null;
		String firstLetter = null;
		StringBuilder strPieceMovement = new StringBuilder(pm.getPieceMovement());
		boolean isCommonMove = true;
		
		if (strPieceMovement.indexOf(Constants.R_CAPITAL_LETTER) == 0 ||
				strPieceMovement.indexOf(Constants.N_CAPITAL_LETTER) == 0 ||
				strPieceMovement.indexOf(Constants.B_CAPITAL_LETTER) == 0 ||
				strPieceMovement.indexOf(Constants.Q_CAPITAL_LETTER) == 0 ||
				strPieceMovement.indexOf(Constants.K_CAPITAL_LETTER) == 0)
		{
			firstLetter = String.valueOf(strPieceMovement.charAt(0));
			strPieceMovement.deleteCharAt(0);
		}
		else if (strPieceMovement.toString().equals(Constants.SHORT_CASTLING))
		{
			isCommonMove = false;
			if (pm.getPieceColor().equals(PieceColor.WHITE))
				GUI.INSTANCE.getFraMainFrame().getPanBoard()
					.makeCastling(PieceColor.WHITE, CastlingSort.SHORT);
			else
				GUI.INSTANCE.getFraMainFrame().getPanBoard()
					.makeCastling(PieceColor.BLACK, CastlingSort.SHORT);
		}
		else if (strPieceMovement.toString().equals(Constants.LONG_CASTLING))
		{
			isCommonMove = false;
			if (pm.getPieceColor().equals(PieceColor.WHITE))
				GUI.INSTANCE.getFraMainFrame().getPanBoard()
					.makeCastling(PieceColor.WHITE, CastlingSort.LONG);
			else
				GUI.INSTANCE.getFraMainFrame().getPanBoard()
					.makeCastling(PieceColor.BLACK, CastlingSort.LONG);
		}
		else
			firstLetter = Constants.EMPTY_STRING;
		
		int checkMarkIndex = strPieceMovement.lastIndexOf(Constants.PLUS_MARK);
		if (checkMarkIndex > 0)
		{
			strPieceMovement.deleteCharAt(checkMarkIndex);
		}
		
		boolean containsCapture = false;
		// boolean containsPromotion = false;
		if (isCommonMove)
		{
			//reset flag
			isCommonMove = false;
			
			if (strPieceMovement.indexOf(Constants.PAUSE_STRING) > 0)
			{
				tab = strPieceMovement.toString().split(Constants.PAUSE_STRING);
				isCommonMove = true;
			}
			else if (strPieceMovement.indexOf(Constants.X_LETTER) > 0)
			{
				tab = strPieceMovement.toString().split(Constants.X_LETTER);
				containsCapture = true;
			}

			if (tab.length != 2)
			{
				String msg = "Game is in invalid state! Format of the game is wrong!";
				JOptionPane.showMessageDialog(null, msg, 
						"Invalid format", JOptionPane.ERROR_MESSAGE);
				logger.error(msg);
				throw new IllegalStateException(msg);
			}
			
			if (tab[1].contains(Constants.EQUAL_MARK))
			{
				isCommonMove = false;
				containsCapture = false;
				//tab = strPieceMovement.toString().split(Constants.EQUAL_MARK);
				//containsPromotion = true;
			}
			
			Piece p = GUI.INSTANCE.getFraMainFrame().getPanBoard().getPiece(tab[0]);
			logger.debug("Chessboard: " + p.getPieceSort());
			logger.debug("Game score result: " + PieceSort.valueOfLetter(firstLetter));
			if (!p.getPieceSort().equals(PieceSort.valueOfLetter(firstLetter)))
			{
				StringBuilder msg = new StringBuilder("Game is in invalid state! Move ")
					.append(firstLetter).append(strPieceMovement)
					.append(" is invalid or piece is on the wrong position!");
				JOptionPane.showMessageDialog(null, msg,
						"Invalid format", JOptionPane.ERROR_MESSAGE);
				logger.error(msg);
				throw new IllegalStateException(msg.toString());
			}
			
			if (isCommonMove)
			{
				int mateMarkIndex = strPieceMovement.lastIndexOf(Constants.HASH_MARK);
				if (mateMarkIndex < 0)
				{
					GUI.INSTANCE.getFraMainFrame().getPanBoard().movePiece(tab[0], tab[1]);
				}
				else
				{
					tab[1] = tab[1].substring(0, tab[1].length()-1);
					GUI.INSTANCE.getFraMainFrame().getPanBoard().movePiece(tab[0], tab[1]);
					String msg = "White won";
					if (pm.getPieceColor().equals(PieceColor.BLACK))
						msg = "Black won";
					JOptionPane.showMessageDialog(null, msg,
							"Result", JOptionPane.INFORMATION_MESSAGE);
				}
				
 
			}
			else if (containsCapture)
				GUI.INSTANCE.getFraMainFrame().getPanBoard().capturePiece(tab[0], tab[1]);
			else //	containsPromotion = true;
			{
				String[] tmp = tab[1].split(Constants.EQUAL_MARK);
				if (tmp.length != 2)
				{
					StringBuilder msg = new StringBuilder("Game is in invalid state! Format of the promotion move: ")
						.append(strPieceMovement).append(" is invalid!");
					JOptionPane.showMessageDialog(null, msg,
							"Invalid format", JOptionPane.ERROR_MESSAGE);
					logger.error(msg);
					throw new IllegalStateException(msg.toString().trim());
				}
				GUI.INSTANCE.getFraMainFrame().getPanBoard().promotePawn(
						tab[0], tmp[0], PieceSort.valueOfLetter(tmp[1]));
			}
		}
	}

	
	private static Logger logger = Logger.getLogger("LOG");
}
